const jwt = require('jsonwebtoken');
const config = require('../config')

module.exports = (req,res,next) => {
    let author = req.header('authorization')
    if(author && author !==''){
        let spaceIndex = author.indexOf(' ')
        let token = author.substring(spaceIndex + 1,author.length)
        const userData = jwt.verify(token,config.secret,(err,decoded) => {
            if(err){
                if(err.name == 'TokenExpiredError'){//token过期
                    return res.status(401).json({
                        code:401,
                        msg:"token已过期,请重新登录"
                    });
                }else if(err.name == 'JsonWebTokenError'){//无效的token
                    return res.status(401).json({
                        code:401,
                        msg:"无效的token"
                    });
                }
            } else {
                return decoded
            }
        })
        req.loginuser = userData
    }
    next()
}